# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 26th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.


from querier.esquerier import ElasticSearchQuerier
import utils.utils as uc
from querier.weibo import utils


class WeiboPostInfoQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type, nlp_service=None):
        super(WeiboPostInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type
        self.nlp_service = nlp_service

    def _build_query(self, args):
        ids = args.get('weibo_ids')
        if ids is None:
            raise ValueError('message: "weibo_ids"(list of "weibo_id") is needed')

        query = {"query": {"terms": {"weibo_id": ids}}, "size": 1000}
        return query, {}, {'weibo_ids': ids}

    def _build_result(self, es_result, param):
        ids = param['weibo_ids']
        articles = []
        for hit in es_result['hits']['hits']:
            data = self.extract_result(hit)
            articles.append((data.get('weibo_id'), data))
        article_dict = dict(articles)
        return {
            "infos": [article_dict.get(i, {}) for i in ids]
        }

    @staticmethod
    def extract_result(hit):
        source_ = hit['_source']
        res = utils.extract_post_from_source(source_)
        res['category'] = uc.category_smzdm_2_decode(source_['category'])
        return res
